package com.hundsun.fcp.webplugin.widget.webview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.SystemClock;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.hundsun.fcp.common.logger.AndroidLogger;
import com.hundsun.fcp.common.logger.Logger;
import com.hundsun.fcp.webplugin.util.SdCardUtil;

public class FcpWebViewClient extends WebViewClient {
	private static final Logger LOGGER = AndroidLogger.getLogger() ;
	private long startTime = 0 ;

	private Context mContext;
	private IWebViewClientEvtHandler mEvtHandler = null;
	public FcpWebViewClient(Context pContext) {
		this.mContext = pContext;
	}
	

	@Override
	public void onPageStarted(WebView view, String url, Bitmap favicon) {
		super.onPageStarted(view, url, favicon);
		LOGGER.debug("FcpWebViewClient onPageStarted") ;
		startTime = System.currentTimeMillis() ;
		if (hasWebVewClientEvtHandler()) {
			this.mEvtHandler.onPageStarted(view, url, favicon, this);
		}
	}

	@Override
	public void onPageFinished(WebView view, String url) {
		LOGGER.debug("FcpWebViewClient onPageFinished") ;
		if (hasWebVewClientEvtHandler()) {
			this.mEvtHandler.onPageFinished(view, url, this);
		}
		LOGGER.debug("加载页面总共使用了："+(System.currentTimeMillis()-startTime)) ;
		super.onPageFinished(view, url);
	}

	@Override
	public void onReceivedError(WebView view, int errorCode,
			String description, String failingUrl) {
		// 404处理
		super.onReceivedError(view, errorCode, description, failingUrl);
	}

	@Override
	public void onReceivedSslError(WebView view, SslErrorHandler handler,
			SslError error) {
		handler.proceed();// 忽略证书的错误继续Load页面内容
	}

	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		if (hasWebVewClientEvtHandler()) {
			return this.mEvtHandler.shouldOverrideUrlLoading(view, url, this);
		} 
		 view.loadUrl(url);
		 return true;
	}

	
	 protected boolean hasWebVewClientEvtHandler()
	  {
	    return this.mEvtHandler != null;
	  }
	 
	 public void setWebViewEvtHandler(IWebViewClientEvtHandler pIWebViewClientEvtHandler)
	  {
	    this.mEvtHandler = pIWebViewClientEvtHandler;
	  }
	
	public static abstract interface IWebViewClientEvtHandler {
		public abstract void onPageFinished(WebView pWebView, String url,FcpWebViewClient pFcpWebViewClient);
		public abstract void onPageStarted(WebView pWebView, String url,Bitmap favicon, FcpWebViewClient pFcpWebViewClient);
		public abstract boolean shouldOverrideUrlLoading(WebView pWebView,String url, FcpWebViewClient pFcpWebViewClient);
	}
}
